<template>
  <div>
    <FixedOperation>
      <!-- 内容 -->
      <div class="text-right">
        <el-button type="primary" @click="save">保存</el-button>
        <el-button type="danger" @click="close">关闭</el-button>
      </div>
    </FixedOperation>
    <title-name title="基本信息" icon="i-carbon-bookmark-filled" />
    <div class="px-5">
      <el-form
        :model="form"
        label-width="110"
        :rules="rules"
        ref="formRef"
        label-position="right"
      >
        <el-row :gutter="formGutter" class="px-10 py-5">
          <el-col :span="formCol">
            <el-form-item label="供应商名称：" prop="bo.supplierName">
              <el-input
                v-model="form.bo.supplierName"
                placeholder="填写供应商名称"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="formCol">
            <el-form-item label="供应商税号：">
              <el-input
                v-model="form.bo.supplierTaxcode"
                placeholder="填写供应商税号"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="formCol">
            <el-form-item label="纳税人性质：">
              <!-- 客户类别 -->
              <el-select
                class="w-full"
                v-model="form.bo.taxNature"
                placeholder="纳税人性质"
                clearable
              >
                <el-option
                  v-for="(dict, index) in tax_grade"
                  :key="index"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="formCol">
            <el-form-item label="行业类型：">
              <el-select
                v-model="form.bo.industryTypeCode"
                placeholder="请选择行业类型"
                class="w-full"
                clearable
              >
                <el-option
                  v-for="(item, index) in industry_category"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="formCol">
            <el-form-item label="归属公司：" required>
              <el-tree-select
                style="width: 100%"
                v-model="form.bo.orgId"
                :data="companyOptions"
                :props="{
                  value: 'id',
                  label: 'label',
                  children: 'children'
                }"
                placeholder="请选择归属公司"
                value-key="id"
                filterable
              />
            </el-form-item>
          </el-col>
          <el-col :span="formCol">
            <el-form-item label="供应商星级：">
              <el-rate v-model="form.bo.starRating" />
            </el-form-item>
          </el-col>
          <el-col :span="formCol">
            <el-form-item label="对接人：" required>
              <el-select
                v-model="form.bo.userId"
                placeholder="请选择归属人员"
                @focus="userInputFocus"
                class="w-full"
              >
                <el-option
                  v-for="(item, index) in selectOptionObj['userId']"
                  :key="index"
                  :label="item.label"
                  :value="item.uuid"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="formCol">
            <el-form-item label="信用等级：">
              <el-select
                v-model="form.co.creditListId"
                placeholder="请选择信用等级"
                class="w-full"
                clearable
              >
                <el-option
                  v-for="(item, index) in credit_rating"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="formCol">
            <el-form-item label="状态：">
              <el-select
                v-model="form.bo.status"
                placeholder="请选择状态"
                class="w-full"
                clearable
              >
                <el-option
                  v-for="(item, index) in supplier_status"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="formCol">
            <el-form-item label="征信积分：">
              <el-input
                v-model="form.co.creditScore"
                placeholder="请输入征信积分"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="formCol">
            <el-form-item label="来源：">
              <el-select
                v-model="form.bo.origin"
                placeholder="请选择来源"
                class="w-full"
                clearable
              >
                <el-option
                  v-for="(item, index) in customer_source"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="formCol">
            <el-form-item label="供应商网址：">
              <el-input
                v-model="form.bo.website"
                placeholder="请输入供应商网址"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="formCol">
            <el-form-item label="所在城市：">
              <el-cascader
                class="w-full"
                clearable
                placeholder="请选择地址"
                style="width: 100%"
                :options="regionData"
                v-model="form.bo.cityCode"
              >
              </el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="formCol">
            <el-form-item label="备注信息：">
              <el-input
                v-model="form.bo.remark"
                placeholder="请输入备注信息"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="formCol">
            <el-form-item label="详细地址：">
              <el-input
                v-model="form.co.address"
                placeholder="请输入详细地址"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <avue-crud
        ref="crud"
        v-model="crudObj"
        :option="option"
        :data="form.contactList"
      >
        <!--   状态   -->
        <template #status="{ row }">
          <dict-tag :options="supplier_status" :value="row.status" />
        </template>
        <template #status-form="{ row }">
          <el-select
            v-model="row.status"
            placeholder="请选择状态"
            class="w-full"
            clearable
          >
            <el-option
              v-for="(item, index) in supplier_status"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </template>
        <!--   角色   -->
        <template #roleCode="{ row }">
          <dict-tag :options="contacts_role" :value="row.roleCode" />
        </template>
        <template #roleCode-form="{ row }">
          <el-select
            v-model="row.roleCode"
            placeholder="请选择角色"
            class="w-full"
            clearable
          >
            <el-option
              v-for="(item, index) in contacts_role"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </template>
        <!--   职务  -->
        <template #dutyCode="{ row }">
          <dict-tag :options="duties_dict" :value="row.dutyCode" />
        </template>
        <template #dutyCode-form="{ row }">
          <el-select
            v-model="row.dutyCode"
            placeholder="请选择职务"
            class="w-full"
            clearable
          >
            <el-option
              v-for="(item, index) in duties_dict"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </template>
        <!--   岗位   -->
        <template #postCode="{ row }">
          <dict-tag :options="post_dict" :value="row.postCode" />
        </template>
        <template #postCode-form="{ row }">
          <el-select
            v-model="row.postCode"
            placeholder="请选择岗位"
            class="w-full"
            clearable
          >
            <el-option
              v-for="(item, index) in post_dict"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </template>
        <template #menu="{ row, index }">
          <el-button
            text
            type="primary"
            :icon="row.$cellEdit ? 'Plus' : 'Edit'"
            @click="rowCell(row, index)"
            >{{ row.$cellEdit ? '保存' : '编辑' }}</el-button
          >
          <el-button
            text
            icon="Delete"
            type="primary"
            @click="rowCancel(row, index)"
          >
            删除</el-button
          >
        </template>
      </avue-crud>

      <!--  弹窗选择组件  -->
      <SelectDialog :dialog-param="dialogParam" @ok="selectData"></SelectDialog>
    </div>
  </div>
</template>
<script setup name="SupplierAddOrUpdate">
import { getCurrentInstance } from 'vue'
import { regionData, CodeToText, TextToCode } from 'element-china-area-data'
import useTagsViewStore from '@/store/modules/tagsView'
import useCommonStore from '@/store/modules/common'
import useUserStore from '@/store/modules/user'
import { getTreeNodeByParam, getUniqueUserId } from '@/utils/commo'
import {
  createSupplier,
  getSupplierInfo,
  updateSupplier
} from '@/api/sourceModules/supplier'
import { getUuid } from '@/utils'

// 通用数据store
const commonStore = useCommonStore()
const userStore = useUserStore()
const { proxy } = getCurrentInstance()
const router = useRouter()
// 字典 具体查看根目录DICT.md文件
const {
  industry_category,
  supplier_status,
  tax_grade,
  credit_rating,
  post_dict,
  duties_dict,
  customer_source,
  invoice_type,
  invoice_header,
  sys_user_sex,
  contacts_role
} = proxy.useDict(
  'industry_category',
  'supplier_status',
  'tax_grade',
  'credit_rating',
  'post_dict',
  'duties_dict',
  'customer_source',
  'invoice_type',
  'invoice_header',
  'sys_user_sex',
  'contacts_role'
)
const activeNames = ref(['info', 'append', 'contacts', 'bill'])
const data = reactive({
  form: {
    bo: {
      origin: '9'
    },
    co: {},
    contactList: []
  },
  updateContactList: [], //用于编辑提交的联系人列表数据
  dialogParam: {}, //弹窗组件配置
  selectOptionObj: {}, // select
  rules: {
    // 联系人姓名
    'bo.supplierName': [
      { required: true, message: '请输入联系人名称', trigger: 'blur' }
    ]
  },
  tableData: [],
  crudObj: {},
  option: {
    rowKey: 'uuid',
    addRowBtn: true,
    addBtn: false,
    delBtn: false,
    columnBtn: false,
    editBtn: false,
    cellBtn: false,
    cancelBtn: false,
    refreshBtn: false,
    column: [
      {
        label: '联系人姓名',
        prop: 'contactName',
        cell: true,
        clearable: true
      },
      {
        label: '联系电话',
        prop: 'contactNumber',
        cell: true,
        clearable: true
      },
      {
        label: '状态',
        prop: 'status',
        cell: true
      },
      {
        label: '角色',
        prop: 'roleCode',
        cell: true
      },
      {
        label: '职务',
        prop: 'dutyCode',
        cell: true
      },
      {
        label: '岗位',
        prop: 'postCode',
        cell: true
      }
    ]
  }
})
const {
  updateContactList,
  tableData,
  option,
  rules,
  form,
  dialogParam,
  selectOptionObj,
  crudObj
} = toRefs(data)
const formCol = ref(12)
const formGutter = ref(20)
const companyOptions = ref([])

/**
 * 获取归属公司数据
 * @returns {Promise<void>}
 */
async function getCompany() {
  // 所属单位列表
  commonStore.getCompanyData().then(data => {
    companyOptions.value = data
  })
}

/**
 * 根据当前用户回填归属人员表单
 */
async function getDefaultUserInfo(userId) {
  let id = ''
  if (userId) {
    id = userId
  } else {
    //获取当前用户id
    id = userStore.user.userId
  }
  //获取部门人员数据
  const deptUserData = await commonStore.getUseTreeData()

  //根据当前用户id获取uuid
  let obj = getTreeNodeByParam(deptUserData, id, 'id', [])

  selectOptionObj.value.userId = obj

  form.value.bo.userId = obj[0].uuid
}

/**
 * 初始化
 * @returns {Promise<void>}
 */
async function init() {
  // 归属公司数据
  await getCompany()
  if (router.currentRoute.value.query.flag == 'add') {
    form.value.bo.orgId = userStore.user.orgId
    await getDefaultUserInfo()
  } else {
    // 获取获取联系人信息
    getSupplierInfoData()
  }
  // 默认归属公司
  form.value.bo.orgId = userStore.user.orgId
}

/**
 * 供应商详情
 */
function getSupplierInfoData() {
  let id = router.currentRoute.value.query.supplierId
  getSupplierInfo(id).then(res => {
    let obj = JSON.parse(JSON.stringify(res.data))
    // 转换城市代码
    if (obj.bo.cityCode != null) {
      obj.bo.cityCode = obj.bo.cityCode.split(',')
    }
    // 转换星级字段属性
    if (obj.bo.starRating != null) {
      obj.bo.starRating = parseInt(obj.bo.starRating)
    }
    getDefaultUserInfo(obj.bo.userId)
    obj.contactList.forEach(item => {
      item.uuid = getUuid()
    })
    form.value = obj
    // 编辑用联系人
    updateContactList.value = JSON.parse(JSON.stringify(form.value.contactList))
  })
}

/**
 * 弹窗选取获取选中的值
 * @param val
 *  type 业务类型
 *     selectData 选中的数据[{value: 1, label: '王晓易', $treeNodeId: 2}]
 *     labelData 选中的数据label ['王晓易']
 *     defaultCheckedKeys 选中的数据id [1]
 *     dialogVisible: false 弹出框的关闭
 */
function selectData(val) {
  console.info('val', val)
  //归属人员
  if (val.type == 'userId') {
    if (!val.selectData.length) {
      form.value.bo[val.type] = ''
    } else {
      selectOptionObj.value[val.type] = val.selectData
      form.value.bo[val.type] = val.defaultCheckedKeys[0]
    }
  }
}

/**
 * 归属人员input获取焦点事件
 */
function userInputFocus() {
  dialogParam.value.type = 'userId'
  dialogParam.value.title = '选择销售经理'
  dialogParam.value.dataType = 'person'
  dialogParam.value.multiple = false
  dialogParam.value.checkStrictly = false
  dialogParam.value.nodeKey = 'uuid'

  // selectOptionObj.value['userId'] = []
  if (form.value.bo['userId'] && form.value.bo['userId'].length) {
    dialogParam.value.isDialog = true
    dialogParam.value.defaultCheckedKeys = [form.value.bo['userId']]
  } else {
    dialogParam.value.isDialog = true
    dialogParam.value.defaultCheckedKeys = []
  }
}

/**
 * 保存方法
 */
function save() {
  proxy.$refs.formRef.validate((valid, fields) => {
    if (valid) {
      let data = JSON.parse(JSON.stringify(toRaw(form.value)))
      if (form.value.bo.cityCode) {
        // 转换所在区域城市编码
        data.bo.cityCode = form.value.bo.cityCode.join(',')
      }
      // 对接人
      if (form.value.bo.userId) {
        console.info('selectOptionObj.value1', selectOptionObj.value)
        // 获取查询到的user数据对象
        let userObj = getUniqueUserId(
          selectOptionObj.value['userId'],
          form.value.bo.userId
        )
        console.info('userObj', userObj)
        //获取userid
        data.bo.userId = userObj.id

        //获取deptId
        data.bo.deptId = userObj.deptId

        //   获取userName
        data.bo.userName = userObj.label
      }

      if (router.currentRoute.value.query.flag == 'add') {
        if (data.contactList.length > 0) {
          let count = data.contactList.findIndex(item => {
            return item['$cellEdit'] == true
          })

          if (count != -1) {
            proxy.$modal.msgWarning('请先保存联系人信息')
            return
          }

          data.contactList.forEach(item => {
            delete item['$cellEdit']
            delete item['$index']
            delete item['_vts']
            item.deptId = data.bo.deptId
            item.orgId = data.bo.orgId
            item.userId = data.bo.userId
            item.delFlag = '0'
            item.entType = '2'
          })
        }
        createSupplier(data).then(res => {
          proxy.$modal.msgSuccess(res.msg)
        })
      } else {
        console.info(updateContactList.value.length)
        if (updateContactList.value.length > 0) {
          let count = updateContactList.value.findIndex(item => {
            return item['$cellEdit'] == true
          })

          if (count != -1) {
            proxy.$modal.msgWarning('请先保存联系人信息')
            return
          }
          updateContactList.value.forEach(item => {
            delete item['$cellEdit']
            delete item['$index']
            delete item['_vts']
            item.deptId = data.bo.deptId
            item.orgId = data.bo.orgId
            item.userId = data.bo.userId
            item.entId = router.currentRoute.value.query.supplierId
            item.entType = '2'
          })

          data.contactList = updateContactList.value
        }

        updateSupplier(data).then(res => {
          proxy.$modal.msgSuccess(res.msg)
        })
      }
    } else {
      console.info('fields', fields)
    }
  })
}

/**
 * 关闭方法
 */
function close() {
  useTagsViewStore().delView(router.currentRoute.value)
  router.go(-1)
}

function rowCell(row, index) {
  // 保存 row.$cellEdit = true    编辑 row.$cellEdit=false
  if (!row.uuid) {
    row.uuid = getUuid()
  }
  if (row.$cellEdit) {
    if (row.contactName == '' || row.contactName == null) {
      proxy.$modal.msgSuccess('联系人姓名不能为空')
      return
    }
    if (row.contactNumber == '' || row.contactNumber == null) {
      proxy.$modal.msgSuccess('联系人电话不能为空')
      return
    }
    if (row.id) {
      // 如果保存的数据存在 则替换提交用的数据
      let i = updateContactList.value.findIndex(item => {
        return item.id == row.id
      })
      if (i) {
        updateContactList.value[i] = row
      }
    } else {
      row.delFlag = '0'
      // 判断是否为新增
      let index = updateContactList.value.findIndex(
        item => item._vts == row._vts
      )

      // 如果为新增 则替换
      if (index != -1) {
        updateContactList.value[index] = row
      } else {
        //否则push新增
        updateContactList.value.push(row)
      }
    }
    console.log(toRaw(updateContactList.value))
    row.$cellEdit = false
  } else {
    row.$cellEdit = true
  }
  // row.$cellEdit = !row.$cellEdit
  // console.log(proxy.$refs.crud, row)
  // proxy.$refs.crud.rowCell(row, index)
}
function rowCancel(row, index) {
  // 取消 row.$cellEdit = true    删除 row.$cellEdit=false
  // console.log('删除|取消', row.$cellEdit)
  // 如果为取消
  // if (row.$cellEdit) {
  //   proxy.$refs.crud.rowCancel(row, index)
  //   proxy.$refs.crud.refreshTable()
  // } else {
  // 删除
  // 存在id
  if (row.id) {
    let index = updateContactList.value.findIndex(item => item.id == row.id)
    if (index != -1) {
      updateContactList.value[index].delFlag = '1'
    }
  } else {
    // 判断是否为新增
    let index = updateContactList.value.findIndex(item => item._vts == row._vts)
    // 如果为新增 则替换
    if (index != -1) {
      updateContactList.value.splice(index, 1)
    }
  }
  form.value.contactList.splice(index, 1)
  console.info('form.value.contactList', form.value.contactList)
  console.info('updateContactList.value', updateContactList.value)
  // }
  // row.$cellEdit = !row.$cellEdit
}

init()
</script>
<style lang="scss" scoped></style>
